<!--
 * @Author: luoyuxiang 398165@qq.com
 * @Date: 2025-03-22 10:34:44
 * @LastEditors: luoyuxiang 398165@qq.com
 * @LastEditTime: 2025-03-23 22:46:34
 * @FilePath: \formula-syn-vue\src\views\project\article\components\TcmEidt.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    <!-- 中医处方表单弹窗 -->
    <el-dialog
      v-model="props.visible"
      :title="dialog.title"
      width="1000px"
      top="3vh"
      @close="handleCloseInLibDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <!-- 名称 -->
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="名称"
            @blur="validateField('name')"
          ></el-input>
        </el-form-item>

        <!-- 中医病名 -->
        <el-form-item label="中医病名" prop="diseaseCn">
          <el-input
            v-model="formData.diseaseCn"
            placeholder="中医病名"
            @blur="validateField('diseaseCn')"
          />
        </el-form-item>

        <!-- 组成 -->
        <el-form-item label="组成" prop="composition" title="点击查看提示">
          <template #label>
            <el-button type="text" @click="handleMessageClick">组成</el-button>
          </template>
          <el-input
            type="textarea"
            :rows="3"
            v-model="formData.composition"
            placeholder="组成"
            @blur="handleCompositionBlur"
          />
        </el-form-item>

        <!-- 其他非必填字段 -->
        <el-form-item label="西医病名" prop="disease">
          <el-input v-model="formData.disease" placeholder="西医病名" />
        </el-form-item>
        <el-form-item label="加减" prop="addSubtract">
          <el-input type="textarea" :rows="2" v-model="formData.addSubtract" placeholder="加减" />
        </el-form-item>
        <el-form-item label="症状" prop="symptom">
          <el-input type="textarea" :rows="2" v-model="formData.symptom" placeholder="症状" />
        </el-form-item>
        <el-form-item label="对证" prop="syndrome">
          <el-input type="textarea" :rows="2" v-model="formData.syndrome" placeholder="对证" />
        </el-form-item>
        <el-form-item label="药效" prop="physiologica">
          <el-input type="textarea" :rows="2" v-model="formData.physiologica" placeholder="药效" />
        </el-form-item>
        <el-form-item label="病因病机" prop="etiolog">
          <el-input type="textarea" :rows="2" v-model="formData.etiolog" placeholder="病因病机" />
        </el-form-item>
        <el-form-item label="原始文本" prop="originalText">
          <el-input
            type="textarea"
            :rows="5"
            v-model="formData.originalText"
            placeholder="原始文本"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit" :disabled="!isFormValid">确定</el-button>
          <el-button @click="handleCloseInLibDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <MessagePrompt code="SPLITTCM" :visible="visibleMessage" @close="visibleMessage = false" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import { ElMessage, ElForm } from "element-plus";
import TcmAPI, { TcmForm } from "@/api/project/tcm";

const props = defineProps({
  id: {
    type: Number,
  },
  articleId: { type: String, required: true },
  articleTitle: {
    type: String,
    required: true,
  },
  visible: {
    type: Boolean,
    required: true,
  },
});

// 监听 visible 的变化
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      handleQuery();
    }
  }
);

const dataFormRef = ref<InstanceType<typeof ElForm>>();
const loading = ref(false);
const isFormValid = ref(false); // 控制按钮是否禁用
const formData = reactive<TcmForm>({});

// 中医处方表单校验规则
const rules = reactive({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  diseaseCn: [{ required: true, message: "请输入中医病名", trigger: "blur" }],
  composition: [{ required: true, message: "请输入组成", trigger: "blur" }],
});

const dialog = reactive({
  title: "",
});

/** 查询中医处方 */
function handleQuery() {
  if (props.id) {
    dialog.title = "修改文章 《" + props.articleTitle + "》 中医处方";
    TcmAPI.getFormData(props.id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    formData.id = undefined;
    dialog.title = "新增文章 《" + props.articleTitle + "》 中医处方";
  }
}

/** 验证单个字段 */
const validateField = async (prop: string) => {
  try {
    await dataFormRef.value?.validateField(prop);
    checkFormValidity(); // 检查表单整体是否通过验证
  } catch (error) {
    isFormValid.value = false; // 验证失败，禁用按钮
  }
};

/** 处理组成输入框失去焦点事件 */
const handleCompositionBlur = async () => {
  await validateField("composition"); // 验证组成字段
  await splitComposition(); // 调用拆分检测
};

/** 调用拆分检测 */
const splitComposition = async () => {
  if (!formData.composition) {
    ElMessage.warning("请填写组成字段后再进行拆分检测");
    return;
  }

  try {
    const requestData = { srtComposition: formData.composition };
    const response = await TcmAPI.splitTcm(requestData);

    isFormValid.value = true; // 表单验证通过，启用按钮
    // ElMessage.success("组成拆分检测成功");
  } catch (error) {
    isFormValid.value = false; // 表单验证失败，禁用按钮
    // ElMessage.error("组成拆分检测失败");
  }
};

/** 检查表单整体是否通过验证 */
const checkFormValidity = async () => {
  try {
    await dataFormRef.value?.validate();
    isFormValid.value = true; // 表单验证通过，启用按钮
  } catch (error) {
    isFormValid.value = false; // 表单验证失败，禁用按钮
  }
};

/** 提交中医处方表单 */
function handleSubmit() {
  dataFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        TcmAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        formData.articleId = Number(props.articleId);
        formData.isSplited = 0;
        TcmAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

const visibleMessage = ref(false);
function handleMessageClick() {
  visibleMessage.value = true;
}

const emit = defineEmits(["resetQuery", "close"]);

const handleResetQuery = () => {
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();

  emit("resetQuery");
};

/** 关闭入库文章导入弹窗 */
function handleCloseInLibDialog() {
  dataFormRef.value?.resetFields();
  dataFormRef.value?.clearValidate();
  emit("close");
}
</script>
